package com.iMusic.integrationLayer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import com.iMusic.businessLogicLayer.Payment;
import com.iMusic.util.Parameters;

public class BankInterface {

    static SSLSocketFactory sslsocketfactory = null;
    static SSLSocket sslsocket = null;

    static InputStream inputstream = null;
    static InputStreamReader inputstreamreader = null;
    static BufferedReader bufferedreader = null;

    static OutputStream outputstream = null;
    static OutputStreamWriter outputstreamwriter = null;
    static BufferedWriter bufferedwriter = null;
    
	/*
	 * Obtains authorization of payment
	 */
	static public boolean authorizePayment(Payment payment) throws UnknownHostException, IOException {
		boolean ret = false;
		
    	 	//if (sslsocket == null || !sslsocket.isBound() || !sslsocket.isConnected()) {
	            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
	            sslsocket = (SSLSocket) sslsocketfactory.createSocket(Parameters.BANK_IP, Parameters.BANK_PORT);

	            inputstream = sslsocket.getInputStream();
	            inputstreamreader = new InputStreamReader(inputstream);
	            bufferedreader = new BufferedReader(inputstreamreader);

	            outputstream = sslsocket.getOutputStream();
	            outputstreamwriter = new OutputStreamWriter(outputstream);
	            bufferedwriter = new BufferedWriter(outputstreamwriter);
	            
	            System.out.println("Connection with bank established.");
    	 	//}
    	 	
    	 	bufferedwriter.write(payment.getCardFlag() + "\n");
            bufferedwriter.write(payment.getCardNumber() + "\n");
            bufferedwriter.write(payment.getExpiryDate() + "\n");
            bufferedwriter.write(payment.getValidationNumber() + "\n");
            bufferedwriter.write(payment.getNameOnCard() + "\n");
            bufferedwriter.write(payment.getTotal() + "\n");
            bufferedwriter.flush();

            String confirmation = bufferedreader.readLine();
            
            if (confirmation.startsWith("OK")) {
            	ret = true;
            }
            
            sslsocket.close();
                		
		return ret;
	}
}
